package com.jt.resource.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.Filter;

//方案二：在过滤器的层面实现跨域配置
//@Configuration
public class CorsFilterConfig {

    /**
     * 定义跨域过滤器的配置，并且将其注册到spring容器中
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> filterFilterRegistrationBean(){

        //1.对此过滤器进行配置(跨域设置-url,method)
        UrlBasedCorsConfigurationSource configSource =
                new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.addAllowedHeader("*");//允许哪种请求头跨域
        corsConfiguration.addAllowedMethod("*");//允许哪种方法类型跨域 get post delete put
        corsConfiguration.addAllowedOrigin("*");// 允许哪些请求源(ip:port)跨域
        corsConfiguration.setAllowCredentials(true);//是否允许携带cookie跨域

        configSource.registerCorsConfiguration("/**", corsConfiguration);

        //2.注册过滤器并设置其优先级
        FilterRegistrationBean<CorsFilter> fbean =
                new FilterRegistrationBean<>(
                        new CorsFilter(configSource));

        fbean.setOrder(Integer.MIN_VALUE);

        return fbean;

    }

}
